from django.contrib.auth.backends import ModelBackend
import re

from .models import User


def get_user_by_account(account):

    """
    根据account判断是用户名还是手机号
    :param account: 用户名或手机号
    :return: user
    """

    try:

        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)

    except User.DoesNotExist:

        return None

    else:

        return user



class UserNameMobileAuthBackend(ModelBackend):

    """修改认证系统，实现多帐号登录"""

    def authenticate(self, request, username=None, password=None, **kwargs):

        """

        :param request: 本次提供的请求提
        :param username: 用户名或手机号
        :param password: 用户密码
        :param kwargs:
        :return: user
        """
        #根据账户去动态查询user
        user = get_user_by_account(username)

        #判断用户是否存在和密码是否正确
        if user and user.check_password(password):

            return user



#重写jwt成功登录后的返回数据，多添加id，username
def jwt_response_payload_handler(token, user=None, request=None):

    return {
        'id': user.id,
        'username': user.username,
        'token': token
    }